//
//  NSObject+Theme.swift
//  ACFrameworkSwift
//
//  Created by c5342925 on 2022/3/31.
//

import Foundation
import UIKit

/// addition properties.
extension NSObject {
    
    struct AssociatedKey {
        static var themeNotification: Void?
        static var themeProvoders: Void?
    }
    
    /// whether had add notification for theme did change
    var isAdditionThemeNotification: Bool {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.themeNotification) as? Bool ?? false
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.themeNotification, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }
    
    var providers: [String: Any] {
        get {
            guard let prov = objc_getAssociatedObject(self, &AssociatedKey.themeProvoders) as? [String: Any] else {
                return [String: Any]()
            }
            return prov
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.themeProvoders, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            if isAdditionThemeNotification == false {
                isAdditionThemeNotification = true
                NotificationCenter.default.addObserver(self, selector: #selector(receiveThemeDidChangeNotification), name: .ThemeDidChange, object: nil)
            }
        }
    }
    
    @objc private func receiveThemeDidChangeNotification() {
        providers.forEach { (_, value: Any) in
            if let closure = value as? (ACThemeStyle) -> Void {
                UIView.animate(withDuration: 0.25) {
                    closure(ACThemeManager.share.currentTheme)
                }
            }
        }
    }
}
